package {
	import com.nbilyk.ntween.NTween;
	
	import fl.motion.easing.Sine;
	
	import flash.display.BlendMode;
	import flash.display.Sprite;
	import flash.events.ContextMenuEvent;
	import flash.events.MouseEvent;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;

	[SWF(width="700", height="500", backgroundColor="#000000")]
	public class NTweenBallExample extends Sprite {
		
		public function NTweenBallExample() {
			super();
			createChildren();
			createContextMenu();
		}
		
		/**
		 * Creates the display objects.
		 */
		protected function createChildren():void {
			
			for (var i:uint = 0; i < 100; i++) {
				var s:BallSprite = new BallSprite();
				s.x = Math.random() * stage.stageWidth;
				s.y = Math.random() * stage.stageHeight;
				
				s.addEventListener(MouseEvent.ROLL_OVER, rollOverHandler);
				
				addChild(s);
			}
		}
		
		/**
		 * On Mouse roll over, tween the ball to the opposite side of the screen.
		 */
		private function rollOverHandler(event:MouseEvent):void {
			var s:BallSprite = BallSprite(event.currentTarget);
			if (NTween.getHasTween(s)) return; // Already tweening.
			var newX:Number = stage.stageWidth - s.x;
			var newY:Number = stage.stageHeight - s.y;
			
			// Tween the target sprite to the new location in 500 milliseconds, and use the Sine.easeOut function.
			NTween.tween(s, { x: newX, y: newY}, 500, 0, Sine.easeOut);
		}
		
		/**
		 * Creates the context menu to show the View Source link.
		 */
		private function createContextMenu():void {
			var newContextMenu:ContextMenu = new ContextMenu();
			var item:ContextMenuItem = new ContextMenuItem("View Source");
			item.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, viewSourceSelectHandler);
			newContextMenu.customItems.push(item);
			contextMenu = newContextMenu;
		}
		
		private function viewSourceSelectHandler(event:ContextMenuEvent):void {
			navigateToURL(new URLRequest("/examples/nTweenBallExample"), "_blank");
		}
	}
}